package com.example.universitylibraryback.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 图书馆事件统一处理器
 */
@Component
public class LibraryEventHandler {
    
    private final ApplicationEventPublisher applicationEventPublisher;
    
    @Autowired
    public LibraryEventHandler(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
    
    /**
     * 处理新书到馆事件
     */
    @EventListener
    @Async("taskExecutor")
    public void handleNewBookArrival(NewBookArrivalEvent event) {
        System.out.println("处理新书到馆事件: " + event.getBookTitle());
        
        try {
            // 通知感兴趣的读者
            notifyReadersAboutNewBook(event);
            
            // 更新推荐系统
            updateRecommendationSystem(event);
            
            // 记录日志
            System.out.println("记录新书到馆日志: " + event.getBookTitle());
            
        } catch (Exception e) {
            System.err.println("处理新书到馆事件失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理借阅到期事件
     */
    @EventListener
    @Async("taskExecutor")
    public void handleBorrowExpiration(BorrowExpirationEvent event) {
        System.out.println("处理借阅到期事件: " + event.getReaderName() + " - " + event.getBookTitle());
        
        try {
            boolean isOverdue = new Date().after(event.getDueDate());
            
            if (isOverdue) {
                // 处理逾期情况
                handleOverdue(event);
            } else {
                // 发送到期提醒
                sendExpirationReminder(event);
            }
            
        } catch (Exception e) {
            System.err.println("处理借阅到期事件失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理罚款计算事件
     */
    @EventListener
    @Async("taskExecutor")
    public void handleFineCalculation(FineCalculationEvent event) {
        System.out.println("处理罚款计算事件: 读者ID=" + event.getReaderId() + ", 逾期天数=" + event.getOverdueDays());
        
        try {
            // 计算罚款金额
            double fineAmount = calculateFine(event.getOverdueDays());
            System.out.println("计算罚款金额: " + fineAmount + "元");
            
            // 这里可以记录罚款信息到数据库
            
        } catch (Exception e) {
            System.err.println("处理罚款计算事件失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理热门图书事件
     */
    @EventListener
    @Async("taskExecutor")
    public void handleHotBook(HotBookEvent event) {
        System.out.println("处理热门图书事件: " + event.getBookTitle() + ", 借阅次数=" + event.getBorrowCount());
        
        try {
            // 增加复本 - 使用固定阈值10
            if (event.getBorrowCount() > 10) {
                System.out.println("建议增加《" + event.getBookTitle() + "》的复本数量");
            }
            
        } catch (Exception e) {
            System.err.println("处理热门图书事件失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理读者活动事件
     */
    @EventListener
    @Async("taskExecutor")
    public void handleReaderActivity(ReaderActivityEvent event) {
        System.out.println("处理读者活动事件: 活动名称=" + event.getActivityName() + ", 活动类型=" + event.getActivityType());
        
        try {
            // 记录读者活动
            String activityDetail = String.format("活动ID: %s, 名称: %s, 时间: %s, 目标读者: %s",
                event.getActivityId(), event.getActivityName(), event.getActivityTime(), event.getTargetReaders());
            System.out.println("记录读者活动: " + activityDetail);
            
        } catch (Exception e) {
            System.err.println("处理读者活动事件失败: " + e.getMessage());
        }
    }
    
    // 辅助方法
    private void notifyReadersAboutNewBook(NewBookArrivalEvent event) {
        System.out.println("通知读者关于新书: " + event.getBookTitle());
        // 模拟通知逻辑
    }
    
    private void updateRecommendationSystem(NewBookArrivalEvent event) {
        System.out.println("更新推荐系统，添加新书: " + event.getBookTitle());
        // 模拟更新逻辑
    }
    
    private void handleOverdue(BorrowExpirationEvent event) {
        long overdueDays = calculateOverdueDays(event.getDueDate());
        System.out.println("处理逾期: 读者=" + event.getReaderName() + ", 逾期天数=" + overdueDays);
        
        // 发布罚款计算事件
        applicationEventPublisher.publishEvent(new FineCalculationEvent(
            event.getReaderId(),
            "BR" + System.currentTimeMillis(),
            (int) overdueDays,
            "借阅逾期"
        ));
    }
    
    private void sendExpirationReminder(BorrowExpirationEvent event) {
        System.out.println("发送到期提醒给读者: " + event.getReaderName());
        // 模拟提醒逻辑
    }
    
    private long calculateOverdueDays(Date dueDate) {
        Date now = new Date();
        long diffTime = now.getTime() - dueDate.getTime();
        return diffTime / (1000 * 60 * 60 * 24);
    }
    
    private double calculateFine(int overdueDays) {
        // 简单的罚款计算逻辑：每天0.5元
        return overdueDays * 0.5;
    }
}